<template>
<view>
<view class="title" v-if="length == 0">
	<view class="choose">
		<view class="checkbox" @tap="bindSelectAll">
			<image :src="selectedAllStatus?'/static/remao_shop/img/xuanzhong_icon.png':'/static/remao_shop/img/weixuanzhong_icon.png'"></image>
		</view>
		<view class="checkall">
			<text>全选</text>
		</view>
	</view>
	<view class="del-title fr" @tap="deleteSelect">
		<text>删除</text>
	</view>
</view>
<view style="width:100%; height:96rpx;"></view>
<view class="container carts-list">
	<view v-for="(item, index) in cartList" :key="index" v-if="length == 0" class="trolley-list" @tap="bindViewTap" :style="windowWidth">
		<image :src="selected[index]?'/static/remao_shop/img/xuanzhong_icon.png':'/static/remao_shop/img/weixuanzhong_icon.png'" @tap="bindCheckbox" :data-index="index"></image>
		<view class="list-left">
			<view class="photo">
				<image :src="item.pic" @tap="toRushdetails" :data-index="index" mode="aspectFill"></image>
			</view>
		</view>
		<view class="list-right fr">
			<view class="carts-text">
				<view class="referral">
					<text class="carts-title" @tap="toRushdetails" :data-index="index">{{item.name}}</text>
				</view>
				<view class="goods">
					<text>{{item.specName}}</text>
				</view>
				<view class="carts-subtitle price">
					<text>￥</text>
					<text class="carts-price">{{item.final_price}}</text>
				</view>
				<view class="but fr">
					<text :class="minusStatuses[index]" :data-index="index" :data-single="item.final_price" @tap="bindMinus">-</text>
					<text type="number" @change="bindManual" class="but-count">{{num[index]}}</text>
					<text class="normal" :data-index="index" :data-single="item.final_price" @tap="bindPlus">+</text>
					<!-- <text class='linshi'> x{{num[index]}} </text> -->
				</view>
			</view>
		</view>
	</view>
	<view style="width:100%; height:96rpx;"></view>
	<view class="bot" v-if="length == 0">
		<view class="choose fl" style="height: 96rpx;line-height: 96rpx;">
			<view class="checkbox" @tap="bindSelectAll">
				<image :src="selectedAllStatus?'/static/remao_shop/img/xuanzhong_icon.png':'/static/remao_shop/img/weixuanzhong_icon.png'"></image>
			</view>
			<view class="checkall">
				<text style="font-size: 30rpx;">全选</text>
			</view>
		</view>
		<view class="total fl" style="width: 240rpx;">
			<text>合计：</text>
			<text style="color:#E51F54; font-size:28rpx;">￥{{allprice}}</text>
		</view>
		<view class="settle fr" @tap="settlement">去结算</view>
	</view>
</view>
<view class="nogoods" v-if="length == 1">
	<view class="nodataimg">
		<image src="/static/remao_shop/img/cart.png" class="nogoodsimg"></image>
	</view>
	<view class="nogoodstext notop">购物车快饿瘪了T.T</view>
	<view class="nogoodstext nobottom">快给我挑宝贝</view>
</view>
</view>
</template>

<script>
import api from "../../../api";
var app = getApp();
var iswe7 = wx.getStorageSync("iswe7");

export default {
  data() {
    return {
      selectedAllStatus: false,
      // total: 0,
      loginModelHidden: !0,
      uid: 0,
      length: 0,
      cartList: [],
      carts: 0,
      num: 0,
      jishu: 1,
      price: [],
      selected: false,
      allprice: 0,
      cart_id: [],
      goods_id: [],
      index: 0,
      windowWidth: '',
      headimg: "",
      showView: ""
    };
  },

  components: {},
  props: {},
  onLoad: function (options) {
    this.getuserID();
    wx.showLoading({
      title: '加载中'
    });
    this.size(); // this.getuserID();

    this.sum(); // this.we7login();

    setTimeout(function () {
      wx.hideLoading();
    }, 500);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var aa = [];

    for (var i = 0; i < this.selected.length; i++) {
      aa[i] = false;
    }

    this.setData({
      selectedAllStatus: false,
      selected: aa
    });
    console.log(this.allprice, '显示');
    this.onLoad();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({
      allprice: 0.00
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      selectedAllStatus: false
    });
    this.onLoad();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  methods: {
    //购物车列表
    trolley: function () {
      var that = this;
      app.globalData.request({
        url: api.default.mycrat,
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值

        },
        method: 'POST',
        data: {
          uid: this.uid
        },
        success: res => {
          console.log(res);

          if (res.msg == '购物车没有商品') {
            this.setData({
              length: 1
            });
          } else {
            var list = [];
            var num = [];
            var price = [];
            var selected = [];
            var c_id = [];
            var g_id = [];
            var img = []; // console.log(res)

            for (var i = 0; i < res.goods_list.length; i++) {
              for (var j = 0; j < res.goods_list[i].list.length; j++) list.push(res.goods_list[i].list[j]);
            }

            console.log(list);

            for (var i = 0; i < list.length; i++) {
              num[i] = parseInt(list[i].num);
              selected[i] = false;
              price[i] = list[i].final_price;
              c_id[i] = list[i].cart_id;
              g_id[i] = list[i].goods_id;
              img[i] = list[i].pic;
            } // console.log(id)


            this.setData({
              headimg: img,
              num: num,
              cartList: list,
              length: 0,
              selected: selected,
              price: price,
              cart_id: c_id,
              goods_id: g_id
            });
            console.log(res);
          }
        }
      });
    },
    //自减
    bindMinus: function (e) {
      var index = parseInt(e.currentTarget.dataset.index);
      var numindex = this.num;
      var newPrice = this.price;
      var single = parseInt(e.currentTarget.dataset.single);
      console.log(single);

      if (numindex[index] > 1) {
        numindex[index] = numindex[index] - 1;
        newPrice[index] = newPrice[index] - single;
        this.setData({
          num: numindex,
          price: newPrice
        });
      } else if (numindex[index] <= 1) {
        wx.showToast({
          title: '数量不能少于1',
          icon: 'none'
        });
      }

      this.sum();
    },
    //自增
    bindPlus: function (e) {
      var index = parseInt(e.currentTarget.dataset.index);
	  console.log(e)
      var single = parseInt(e.currentTarget.dataset.single);
      var numindex = this.num;
	  console.log(numindex)
      numindex[index] = numindex[index] + 1;
      var newPrice = this.price;
      newPrice[index] = newPrice[index] + single;
      this.setData({
        num: numindex,
        price: newPrice
      });
      this.sum();
    },
    bindCheckbox: function (e) {
      var index = parseInt(e.currentTarget.dataset.index); // //原始的icon状态

      var selected = this.selected;
      selected[index] = !selected[index];
      this.setData({
        selected: selected
      });
      this.sum();
    },
    //点击列表按钮，判断是否全选
    bindViewTap: function () {
      var selected = this.selected;
      var a = this.selectedAllStatus; // console.log(a)

      var num = 0;

      for (var i = 0; i < selected.length; i++) {
        if (selected[i] == true) {
          num++;
        }
      }

      if (num == selected.length) {
        a = true;
      } else if (num < selected.length) {
        a = false;
      }

      this.setData({
        selectedAllStatus: a
      });
    },
    bindSelectAll: function () {
      var selectedAllStatus = this.selectedAllStatus;
      var selected = this.selected;
      selectedAllStatus = !selectedAllStatus;

      if (selectedAllStatus == true) {
        for (var i = 0; i < selected.length; i++) {
          selected[i] = true;
        }
      } else if (selectedAllStatus == false) {
        for (var i = 0; i < selected.length; i++) {
          selected[i] = false;
        }
      }

      this.setData({
        selectedAllStatus: selectedAllStatus,
        selected: selected
      });
      this.sum();
    },
    sum: function () {
      // var price = this.data.price,
      //   selected = this.data.selected;
      //    num = this.data.num;
      // var index = [];
      //  var n = 0;
      //  for (var i = 0; i < selected.length; i++) {
      //    if (selected[i] == true) {
      //      index[n] = i
      //      n++
      //    }
      //  }
      // var allpice = 0,
      //   j = 0
      // for (var i = 0; i < index.length; i++) {
      //   j = index[i]
      //   // allpice += price[j] * num[j]
      //   allpice += price[j]
      // }
      var price = this.price,
          selected = this.selected;
      console.log(price);
      var allpice = 0;
      console.log(this.selected);

      for (var i = 0; i < selected.length; i++) {
        if (selected[i] == true) {
          console.log(i);
          allpice += price[i];
        }
      }

      allpice = allpice.toFixed(2);
      this.setData({
        allprice: allpice
      });
      console.log(this.allprice);
    },

    getuserID() {
      // console.log('我被调用了')
      wx.getStorage({
        key: 'userId',
        success: res => {
          this.setData({
            uid: res.data
          });
          this.trolley();
        },
        fail: res => {
          console.log(res);
          wx.showToast({
            title: '请先登录'
          });
          setTimeout(function () {
            if (iswe7 == 1) {
              wx.navigateTo({
                url: '../../packageA/login/login'
              });
            } else {
              wx.navigateTo({
                url: '../../packageA/logins/login'
              });
            }
          }, 2000);
        }
      });
    },

    //删除
    deleteSelect() {
      var selected = this.selected,
          cart_id = this.cart_id;
      var l = 0,
          id = '';

      for (var i = 0; i < selected.length; i++) {
        if (selected[i] == true) {
          if (i == selected.length - 1) {
            id += cart_id[i];
          } else {
            id += cart_id[i] + ',';
          }

          l++;
        }
      }

      if (l > 0) {
        wx.showModal({
          // title: '确认删除',
          content: '确定要删除这个商品吗？',
          success: res => {
            if (res.confirm) {
              app.globalData.request({
                url: api.default.delcrat,
                header: {
                  'content-type': 'application/x-www-form-urlencoded' // 默认值

                },
                method: 'POST',
                data: {
                  uid: this.uid,
                  cart_id: id
                },
                success: res => {
                  var aa = [];

                  for (var i = 0; i < this.selected.length; i++) {
                    aa[i] = false;
                  }

                  this.setData({
                    selected: aa
                  });
                  wx.showToast({
                    title: res.msg
                  });
                  this.onLoad();
                }
              });
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        });
      }
    },

    // 去结算
    settlement() {
      console.log(this.cart_id);
      var selected = this.selected,
          cart_id = this.cart_id;
      console.log(selected);
      var l = 0,
          id = '';

      for (var i = 0; i < selected.length; i++) {
        if (selected[i] == true) {
          if (i == selected.length - 1) {
            id += cart_id[i];
          } else {
            id += cart_id[i] + ',';
          }

          l++;
        }
      }

      console.log(id);

      if (id) {
        wx.navigateTo({
          url: '../../packageA/affirm/affirm?type=' + 1 + '&userId=' + this.uid + '&cart_id=' + id
        });
      } else {
        wx.showToast({
          title: '请选择商品'
        });
      }
    },

    //路由
    toRushdetails(e) {
      console.log(e);
      var i = e.currentTarget.dataset.index;
      var id = this.goods_id[i];
      var img = this.headimg[i];
      wx.navigateTo({
        url: '../../packageA/rushdetails/rushdetails?goods_id=' + id + '&img=' + img
      });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    //获取屏幕尺寸
    size() {
      wx.getSystemInfo({
        success: res => {
          // console.log(res);
          // 屏幕宽度、高度
          // console.log('width=' + res.windowWidth);
          // 高度,宽度 单位为px
          this.setData({
            windowWidth: 'width:' + res.windowWidth - 5 + 'px'
          });
        }
      });
    },

    onChangeShowState: function () {
      var that = this;
      that.setData({
        showView: !that.showView
      });
    }
  }
};
</script>
<style>
@import "./trolley.css";
</style>